package org.pms.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.pms.dao.AdministratorsDao;
import org.pms.entity.Administrators;
import org.pms.util.C3P0Util;

import java.sql.SQLException;
import java.util.List;

/**
 *  StaffDAO接口的实现类 - 基于C3P0 + DbUtils实现的数据库的增、删、改、查操作
 * @Date 2023-03-09
 * @Author 祝世栩
 */
public class AdministratorsDaoImplC3P0 implements AdministratorsDao {
    // 实例化 QueryRunner 对象 - DbUtils工具的核心对象，对原生JDBC操作做了封装，用于执行SQL语句
    private QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());

    String sql = null ;

    @Override
    public Administrators AdministratorsSelectNumberPwd(String Number, String Pwd) {
        // 第一：定义要操作数据库的SQL语句
        // 注意：使用别名解决实体对象属性名和数据表字段名不一致的问题
        sql = "select Administrators_Number as administratorsNumber , Administrators_Pwd as administratorsPwd from Administrators where administratorsNumber = ? and administratorsPwd = ?";
        try {
            return qr.query(sql,new BeanHandler<Administrators>(Administrators.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Administrators> AdministratorsSelectAll() {
        sql = "select Administrators_Number as administratorsNumber,Administrators_Pwd as administratorsPwd from Administrators";
        try {
            return qr.query(sql,new BeanListHandler<Administrators>(Administrators.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int AdministratorsInsert(Administrators administrators) {
        sql = "insert into Administrators(Administrators_Number,Administrators_Pwd) values(?,?)";
        try {
            Object[] params = new Object[]{administrators.getAdministratorsNumber(),administrators.getAdministratorsPwd()};
            return qr.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int AdministratorsUpdate(Administrators administrators) {
        sql = "update Administrators set Administrators_Pwd = ? where Administrators_Number = ? ";
        try {
            return qr.update(sql,administrators.getAdministratorsPwd(),administrators.getAdministratorsNumber());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
